package middleware

import (
	"github.com/gin-gonic/gin"
	"log"
	"oa_kadia_link/config"
	"oa_kadia_link/globe"
	"oa_kadia_link/utils"
	"reflect"
)

func Transaction() gin.HandlerFunc {
	return func(context *gin.Context) {
		transaction := globe.GetMdb().Begin()
		if config.GetEnv().DevMode {
			transaction = transaction.Debug()
		}
		defer func() {
			if err := recover(); err != nil {
				transaction.Rollback()
				flag := utils.GetErrorJsonFlag()
				errMsg := "服务器错误，请重试！"
				if reflect.TypeOf(err).String() == "string" && utils.StringPrefix(err.(string), flag) {
					errMsg = err.(string)[len(flag):]
				} else {
					log.Println(err)
				}
				context.Set("errJson", errMsg)
				utils.ErrorJSON(context, errMsg)
			}
		}()
		context.Set("transaction", transaction)
		context.Next()
		transaction.Commit()
		if json, exists := context.Get("json"); exists == true {
			utils.SuccessJSON(context, json)
		} else {
			utils.SuccessJSON(context, nil)
		}
	}
}
